package com.ht.shop.service.impl;

import com.ht.shop.dao.OrderDao;
import com.ht.shop.dao.impl.OrderDaoImpl;
import com.ht.shop.pojo.CartItem;
import com.ht.shop.pojo.Order;
import com.ht.shop.service.OrderService;

import java.util.List;
import java.util.UUID;

public class OrderServiceImpl implements OrderService {
    private OrderDao orderDao = new OrderDaoImpl();

    @Override
    public Order createOrder(List<CartItem> cartItemList, String aid) {
        if (cartItemList != null && cartItemList.size() > 0) {
            String oid = UUID.randomUUID().toString().replaceAll("-", "");
            //计算总价
            long total = cartItemList.stream().mapToLong(CartItem::getTotalPrice).sum();
            Long uid = cartItemList.get(0).getUid();
            orderDao.addOrder(oid, uid, total, aid);

            cartItemList.forEach(cartItem -> {
                long id = cartItem.getId();
                long totalPrice = cartItem.getTotalPrice();
                int num = cartItem.getNum();
                orderDao.addOrderDetail(oid, id, num, totalPrice);
            });
            Order order = new Order();
            order.setMoney(total);
            order.setId(oid);
            return order;
        }
        return null;
    }

    @Override
    public void processPay(String id) {
        String status = orderDao.findStatusById(id);
        if ("0".equalsIgnoreCase(status)) {
            orderDao.updateStaus2Success(id);
        }else {
            System.err.println("当前订单状态异常,无法更新为支付状态");
        }
    }
}
